from django.core.cache import caches


"""
 装饰器[传参]
"""
def cache_check(**cache_kwargs):
    def _cache_check(func):
        def warpper(self, request, *args, **kwargs):
            """
                装饰器逻辑加强
                详情页面数据存储
                构建可传参的装饰器：自定义缓存key
                :param:cache_kwargs:将装饰器的参数打包为字典
                cache_kwargs{'key_prefix': 'gd', 'key_param': 'sku_id', 'cache': 'goods_detail', 'expire': 300}
                kwargs{'sku_id': 2}
            """
            CACHES = caches[cache_kwargs.get("cache", "default")]
            key = cache_kwargs['key_prefix'] + str(kwargs.get('sku_id'))
            response = CACHES.get(key)
            if response:
                return response
            # redis中没有，到mysql数据库中获取并缓存到redis
            value = func(self, request, *args, **kwargs)
            exp = cache_kwargs.get("expire", 60)
            CACHES.set(key, value, exp)
            return value
        return warpper
    return _cache_check